<template>

  <div class="pages goodsgoodEditnew">
    
    <div class="pageLevel">
      <el-tabs v-model="activeName2" type="card" @tab-click="handleClick" style="margin-top:30px;">
        <el-tab-pane label="基本信息" name="first">
          <el-form :model="ruleForm" :rules="rules" ref="ruleForm" label-width="100px" class="demo-ruleForm goodsbatchs">
            <div class="from_main infon">
              <el-row>
                <el-col :span="4">
                  <el-form-item class="rowtwo" label="">
                    <!-- 输入基本信息 -->
                    <el-checkbox :disabled="commodityModificationStore" v-model="ruleForm.checked" label="启用" true-label="0" false-label="1"></el-checkbox>
                  </el-form-item>
                </el-col>
              </el-row>
              <el-row>
                <el-col :span="8">
                  <el-form-item class="rowtwo" label="商品名称" prop="name" label-width="150px">
                    <el-input v-if="showTabs == true" :disabled="commodityModificationDis||commodityModificationStore||commodityModification" v-model="ruleForm.name" maxlength="40" size="small"></el-input>
                    <span class="span" v-if="showTabs == false">{{ruleForm.name}}</span>
                  </el-form-item>
                </el-col>
                <el-col :span="6">
                  <el-form-item class="rowtwo rowsecond" label="商品条码" prop="barCode">
                    <el-input v-if="showTabs == true" :disabled="commodityModificationDis||commodityModificationStore||commodityModification" v-model="ruleForm.barCode" maxlength="13" size="small"></el-input>
                    <span class="span" v-if="showTabs == false">{{ruleForm.barCode}}</span>
                  </el-form-item>
                </el-col>
                <el-col :span="8">
                  <el-form-item class="rowtwo rowsecond" label="商品货号" prop="productCode" label-width="150px">
                    <el-input v-if="showTabs == true" :disabled="commodityModificationDis||commodityModificationStore||commodityModification" v-model="ruleForm.productCode" maxlength="13" size="small"></el-input>
                    <span class="span" v-if="showTabs == false">{{ruleForm.productCode}}</span>
                  </el-form-item>
                </el-col>
              </el-row>
              <el-row>
                <el-col :span="8">
                  <el-form-item class="rowtwo rowsecond" label="商品分类(品类)" label-width="150px" prop="selectedOptions">
                    <el-cascader v-if="showTabs == true" size="small" :disabled="commodityModificationDis||commodityModificationStore||commodityModification" props.expandTrigger="hover" :options="classType" v-model="ruleForm.selectedOptions">
                    </el-cascader>
                    <el-cascader class="cascaderClass" v-if="showTabs == false" size="small" :disabled="commodityModificationDis||commodityModificationStore||commodityModification" props.expandTrigger="hover" :options="classType" v-model="ruleForm.selectedOptions">
                    </el-cascader>
                  </el-form-item>
                </el-col>
                <el-col :span="6">
                  <el-form-item class="rowtwo" label="品牌" prop="brandName">
                    <el-input v-if="showTabs == true" placeholder="请输入内容" size="small" v-model="ruleForm.brandName" class="input-with-select" :disabled="true">
                      <el-button type="primary" :disabled="commodityModificationDis||commodityModificationStore||commodityModification" @click="dialogTableVisible=true" slot="append">选择</el-button>
                    </el-input>
                    <span class="span" v-if="showTabs == false">{{ruleForm.brandName}}</span>
                  </el-form-item>
                </el-col>
                <el-col :span="8">
                  <el-form-item class="rowtwo" label="税率" prop="incomeTaxRates" label-width="150px">
                    <el-input v-if="showTabs == true" style="width:120px" :disabled="commodityModification" v-model="ruleForm.incomeTaxRates" maxlength="8" size="small"></el-input>
                    <span class="span" v-if="showTabs == false">{{ruleForm.incomeTaxRates}}</span>
                    <span>%</span>

                  </el-form-item>
                </el-col>
              </el-row>
              <el-row>
                <el-col :span="7">
                  <el-form-item class="rowtwo" label="启用批次管理" prop="seasonalMarkingSwitch" label-width="150px">
                    <el-radio-group :disabled="commodityModificationStore||commodityModification||seasonalMarkingSwitchs" v-model="ruleForm.seasonalMarkingSwitch">
                      <el-radio label="1">是</el-radio>
                      <el-radio label="0">否</el-radio>
                    </el-radio-group>
                  </el-form-item>
                </el-col>
                <el-col :span="7">
                  <el-form-item class="rowtwo" label="散装称重" prop="whether" label-width="150px">
                    <el-radio-group :disabled="commodityModificationStore||commodityModification" v-model="ruleForm.whether">
                      <el-radio label="1">是</el-radio>
                      <el-radio label="0">否</el-radio>
                    </el-radio-group>
                  </el-form-item>
                </el-col>
                <el-col :span="7">
                  <el-form-item class="rowtwo" label="保质期" prop="expirationDate" label-width="150px">
                    <el-input style="width:120px;" @blur="changeExpirationDate" v-if="showTabs == true" :disabled="commodityModificationDis||commodityModificationStore||commodityModification" v-model="ruleForm.expirationDate" maxlength="4" size="small"></el-input>
                    <span class="span" v-if="showTabs == false">{{ruleForm.expirationDate}}</span>
                    <span>天</span>
                  </el-form-item>
                </el-col>
              </el-row>
              <el-row>
                <el-col :span="8">
                  <el-form-item v-if="storeYin" class="rowtwo" label="已分配商户" prop="orgAllocated" label-width="150px">
                    <span style="width:530px;display:inline-block;color:#333;font-size:13px;">{{ruleForm.orgAllocated}}</span>
                  </el-form-item>
                </el-col>
                <el-col :span="9" v-if="isShop ==1">
                  <el-form-item class="rowtwo" label="是否提成" label-width="95px">
                    <el-radio-group v-model="ruleForm.isCommission" :disabled="alloted || !showTabs || ruleForm.orgAllocated.length > 0">
                      <el-radio label="0">是</el-radio>
                      <el-radio label="1">否</el-radio>
                    </el-radio-group>
                  </el-form-item>
                  <el-form-item label="选择提成方式" v-if="ruleForm.isCommission=='0'" label-width="100px">
                    <!-- {{ruleForm.orgAllocated}} -->
                    <el-select v-model="ruleForm.commissionType" size="small" class="limit-width" :disabled="alloted ||!showTabs || ruleForm.orgAllocated.length > 0">
                      <el-option label="比例提成" value="0"></el-option>
                      <el-option label="固定提成" value="1"></el-option>
                    </el-select>
                    <el-input v-model="ruleForm.number" size="small" class="limit-width" :disabled="alloted ||!showTabs"></el-input>
                    <span v-if="ruleForm.commissionType == 0">%</span>
                    <span v-else>元</span>
                  </el-form-item>
                </el-col>
              </el-row>
            </div>
          </el-form>
          <div class="infon_text">
            <span class="infon_shu"></span>
            <el-button type="primary" :disabled="commodityModificationStore||commodityModification" @click="addsize()" size="mini">添加规格型号</el-button>
          </div>
          <div style="width:90%;margin:40px auto;" v-if="specificationsList.length>0">
            <el-table ref="singleTable" :data="specificationsList" highlight-current-row style="width: 100%">
              <el-table-column type="index" label="序号" width="50">
              </el-table-column>
              <el-table-column prop="paramName" label="规格型号名称" align="center"></el-table-column>
              <el-table-column prop="paramValue" label="规格型号值" align="center">
              </el-table-column>
              <el-table-column prop="remark" label="备注" align="center"></el-table-column>
            </el-table>
          </div>
        </el-tab-pane>
        <el-tab-pane label="基本单位" name="second">
          <el-form :model="unitIdForm" :rules="unitIdRules" ref="unitIdForm" label-width="100px" style="margin-top:20px;" class="demo-unitIdForm goodsbatchs">
            <el-form-item class="rowtwo rowsecond" label="基本单位" prop="unitId">
              <el-select v-if="showTabs == true" v-model="unitIdForm.unitId" placeholder="请选择基本单位" size="small" :disabled="commodityModificationStore||commodityModification" @change="changeUnitId">
                <el-option v-for="item in options2" :key="item.index" :label="item.name" :value="item.id"></el-option>
              </el-select>
              <span class="span" v-if="showTabs == false">{{unitIdForm.unitId}}</span>
            </el-form-item>
          </el-form>
          <!-- 包装规格 -->
          <!-- 操作框 -->
          <div class="operationBox tableSearch" style="margin-left:10px;margin-top:-30px;">
            <el-button type="primary" :disabled="commodityModificationStore||commodityModification" @click="addUnitId()" size="mini">新增</el-button>
          </div>
          <!-- 表格 -->
          <div class="tableMain">
            <el-table ref="multipleTable" height="350" :data="tableDataUnitId" stripe style="width: 90%;margin:20px auto">
              <el-table-column prop="quantityBefor" label="" align="center">
              </el-table-column>
              <el-table-column prop="goodsUnitId" align="center" label="包装单位">
                <template slot-scope="scope">
                  <el-select :disabled="commodityModificationStore||commodityModification" v-model="scope.row.goodsUnitId" placeholder="请选择" size="small">
                    <el-option size="small" v-for="item in options2" :key="item.id" :label="item.name" :value="item.id"></el-option>
                  </el-select>
                </template>
              </el-table-column>
              <el-table-column prop="unitNum" label="数量" align="center" width="250">
                <template slot-scope="scope">
                  <input class="commonInput" style="height:30px;width:200px;" :disabled="commodityModification" v-if="showTabs == true" clearable maxlength="50" v-model="scope.row.unitNum" placeholder="请输入换算后数量" size="small" oninput="if(this.value.length==1){this.value=this.value.replace(/[^1-9]/g,'')}else{this.value=this.value.replace(/\D/g,'')}" onafterpaste="if(this.value.length==1){this.value=this.value.replace(/[^1-9]/g,'0')}else{this.value=this.value.replace(/\D/g,'')}">
                  <span v-if="showTabs == false">{{scope.row.unitNum}}</span>
                </template>
              </el-table-column>
              <el-table-column prop="baseUnitName" label="单位" align="center">
                <template slot-scope="scope">
                  <span>{{scope.row.baseUnitName}}</span>
                </template>
              </el-table-column>
              <el-table-column prop="isShow" label="采供单位" align="center">
                <template slot-scope="scope">
                  <div>
                    <el-radio :disabled="commodityModificationStore||commodityModification" @change.native="changeCheckbox(scope.$index,scope.row)" v-model="isShow" :label="scope.$index">&nbsp;</el-radio>
                  </div>
                </template>
              </el-table-column>
              <el-table-column prop="name" align="center" label="操作" width="180">
                <template slot-scope="scope">
                  <el-button size="small" :disabled="commodityModificationStore||commodityModification" @click="cancelUnitId(scope.$index,tableDataUnitId)" type="text" class="addDetail">删除</el-button>
                </template>
              </el-table-column>
            </el-table>
            <!-- 页码 -->

          </div>
        </el-tab-pane>
        <el-tab-pane label="商品知识" name="third" v-if='setRole("商品知识")'>
          <goods-reading :goodsName='ruleForm.name' :brandName='ruleForm.brandName' :brandId='arr != "" ? arr : brandId' :activeName2='activeName2' ref="mychild"></goods-reading>
        </el-tab-pane>
      </el-tabs>
      <!-- 弹出框品牌 -->
      <el-dialog title="品牌选择" class="addshopname" :visible.sync="dialogTableVisible" :closeOnClickModal='false' :closeOnPressEscape='false'>
        <i class="el-icon-close icon" @click="dialogTableVisible=false"></i>
        <div class="operationBox tableSearch">
          <el-button size="mini" type="primary" @click="xzbrands()">选择</el-button>
          <el-button size="mini" @click="dialogTableVisible=false">取消</el-button>
        </div>
        <div class="serch">
          <el-input placeholder="输入品牌编码或品牌名称" v-model="brandnames" size="small"></el-input>
          <el-button type="primary" size="small" class="serchcha" @click="shopserch">查询</el-button>

        </div>
        <el-table ref="singleTable" :data="tableData" highlight-current-row @current-change="changeFun" style="width: 100%">
          <el-table-column type="index" label="序号" width="50">
          </el-table-column>
          <el-table-column prop="code" label="品牌编号" align="center"></el-table-column>
          <el-table-column prop="name" label="品牌名称" align="center"></el-table-column>
        </el-table>
        <div class="pageblock pageinput">
          <el-button size="small" type="primary" class="Determine topage" @click="toPage">确定</el-button>
          <el-pagination @size-change="handleSizeChange" @current-change="handleCurrentChange" :current-page="currentPage" :page-sizes="[20,30]" :page-size="pageSize" layout="total, sizes, prev, pager, next, jumper" :total="total">
          </el-pagination>
        </div>
      </el-dialog>
      <el-dialog title="新增规格型号" class="addshopname" :visible.sync="dialogTableVisible1" :closeOnClickModal='false' :closeOnPressEscape='false'>
        <i class="el-icon-close icon" @click="dialogTableVisible1=false"></i>
        <div class="serch">
          <el-input placeholder="输入规格型号" v-model="specifications" size="small"></el-input>
          <el-button type="primary" size="small" class="serchcha" @click="specificationsSerch">查询</el-button>
        </div>
        <el-table ref="singleTable" :data="tableDataSpecifications" highlight-current-row @selection-change="changeFunSpecifications" height="200" style="width: 100%">
          <!-- <el-table-column type="index" label="序号" width="50">
          </el-table-column> -->
          <el-table-column type="selection" width="55">
          </el-table-column>
          <el-table-column prop="paramName" label="规格型号名称" align="center"></el-table-column>
          <el-table-column prop="value" label="规格型号值" align="center" width="300">
            <template slot-scope="scope">
              <el-select v-model="scope.row.radiospe" filterable placeholder="请选择" size="mini" style="width:130px;">
                <el-option v-for="(item,index) in scope.row.value" :key="index" :label="item.paramValue" :value="item.id"></el-option>
              </el-select>
            </template>
          </el-table-column>
          <el-table-column prop="remark" label="备注" align="center"></el-table-column>
        </el-table>
        <div class="pageblock pageinput">
          <el-button size="small" type="primary" class="Determine topage" @click="toPageSpecifications">确定</el-button>
          <el-pagination @size-change="handleSizeChangeSpecifications" @current-change="handleCurrentChangeSpecifications" :current-page="currentPageSpe" :page-sizes="[20,30]" :page-size="pageSizeSpe" layout="total, sizes, prev, pager, next, jumper" :total="totalSpe">
          </el-pagination>
        </div>
        <div slot="footer" class="dialog-footer goodsFooter">
          <el-button @click="cancelSpe" size="small">取 消</el-button>
          <el-button type="primary" @click="submitFormSpe()" size="small">确 定</el-button>
        </div>
      </el-dialog>
      <!-- 操作框 -->
      <div class="operationBox tableSearch" style='text-align: center;padding-bottom: 80px'>
        <el-button type="primary" @click="goBack" plain>返回</el-button>
        <el-button type="primary" v-if="showTab == '3'" @click="save('ruleForm')">保存</el-button>
        <el-button type="primary" v-show="storeYin" v-if="showTab == '1'&&setRole('修改')" @click="goodEdit()">修改</el-button>
      </div>
    </div>
  </div>
</template>
<script>
import { mapState } from "vuex";
import goodsReading from "./components/index";
import merge from "webpack-merge";
import {
  updateGoods,
  getGoodsDetail,
  getGoodsParameterListByPage,
  getGoodsUnitList,
  getGoodsLabelList,
  getGoodsClassifyTreeList
  //新增接口
} from "@/api";
import util from "@/util";
export default {
  computed: mapState([
    "merchantId",
    "userInfo",
    "sub",
    "power",
    "soUrce",
    "isShop"
  ]),
  data() {
    return {
      alloted: null,
      isCommision: 1,
      activeName2: "first",
      options2: [], //单位数组
      classType: [], //商品品类
      brandname: "",
      dialogTableVisible: false, //品牌弹窗
      brandnames: "", //品牌查询中的品牌查询值
      dialogTableVisible1: false, //新增规格弹窗
      ruleForm: {
        checked: "0", //启用停用
        retailState: "1", //零售上架
        name: "", //商品名称
        selectedOptions: [], //商品品类
        brandName: "", //品牌
        barCode: "", //商品条码
        productCode: "", //商品货号
        unitId: "", //库存成本单位
        incomeTaxRates: "", //进项税率
        orgAllocated: "", //已分配组织机构
        seasonalMarkingSwitch: "0", //是否启用批次管理
        whether: "0", //是否散装称重
        expirationDate: "", //保质期
        isCommission: "1",
        commissionType: "0",
        number: ""
      },
      rules: {
        name: [
          { required: true, message: " 请输入商品名称", trigger: "blur" },
          { max: 40, message: "长度在40个字符之内", trigger: "blur" },
          { validator: util.valida, trigger: "blur", required: true }
        ],
        selectedOptions: [
          { required: true, message: " 请选择商品分类", trigger: "blur" }
        ],
        brandName: [
          { required: true, message: " 请选择品牌", trigger: "blur" }
        ],
        barCode: [
          { required: true, message: " 请输入商品条码", trigger: "blur" },
          {
            validator: util.validateParkingLot,
            trigger: "blur",
            required: false
          },
          { validator: util.valida, trigger: "blur", required: true }
        ],
        productCode: [
          { required: false, message: " 请输入商品货号", trigger: "blur" },
          {
            validator: util.validateParkingLot,
            trigger: "blur",
            required: false
          }
        ],
        expirationDate: [
          { required: false, message: " 请输入保质期", trigger: "blur" },
          {
            validator: util.validateParkingLot,
            trigger: "blur",
            required: false
          }
        ],
        incomeTaxRates: [
          {
            validator: util.validatenum,
            trigger: "blur",
            required: false
          },
          {
            validator: util.valida,
            trigger: "blur",
            required: false
          }
        ]
      },
      unitIdForm: {
        unitId: ""
      }, //包装规格字段验证
      unitIdRules: {
        unitId: [{ required: true, message: " 请选择单位", trigger: "blur" }]
      }, //包装规格
      tableDataUnitId: [], //包装规格里面的数据
      currentPageUnitId: 1,
      totalUnitId: 0,
      pageSizeUnitId: 20,
      totalItemsUnitId: 0,
      dis: false,
      isShow: "", //包装规格中的采装单位
      tableData: [], //品牌弹窗中的数组
      xzbrand: [], //选择品牌的一条数据
      arr: "", //选择品牌的id
      arrname: [], //选择品牌的名称
      // 分页开始
      total: 0,
      pageSize: 20,
      totalItems: 0,
      currentPage: 1,
      // 弹窗规格型号初始化
      tableDataSpecifications: [],

      totalSpe: 0,
      pageSizeSpe: 20,
      totalItemsSpe: 0,
      currentPageSpe: 1,
      radiospe: "0", //规格型号绑定的值
      specificationsValue: "", //规格型号选定的值
      specificationsList: [], //规格型号的数组
      commodityModificationDis: false, //公司不能修改的
      commodityModificationCheck: false, //启用停用
      commodityModificationStore: false, //查看时不能修改
      commodityModification: false, //停用时下面的数据不能修改
      status: "", //查看详情时启用停用的状态
      optionsName: "", //最小单位的值
      unitIdName: "", //包装规格数组里面最小单位的值
      showTabs: null,
      showTab: null,
      adds: [],
      unitIdData: "",
      indexI: "",
      specificationsValueArr: [],
      detailvalueId: [], //查看详情时的规格型号的选择的id
      brandId: "", //查看详情时的品牌id
      unitIdval: "", //选择的基本单位的id
      goodsUnitIdVals: "", //查看详情时的基本单位的id
      specifications: "",
      seasonalMarkingSwitchs: false,
      storeYin: true //当是门店时显示已分配商户和修改不可见(是否分配过门店)
    };
  },
  components: {
    goodsReading
  },
  created() {
    this.showTab = util.getQuery("showTab");
    let boo = util.getQuery("alloted");
    this.alloted = boo == "true" ? true : false;
    // 点击修改过来的
    if (this.showTab == "3") {
      if (util.getQuery("isReading") == "1") {
        this.activeName2 = "third";
      }
      this.showTabs = true;
      this.commodityModificationDis = false;
      this.commodityModificationStore = false;
    }
    // 点击查看过来的
    if (this.showTab == "1") {
      if (util.getQuery("isReading") == "1") {
        this.activeName2 = "third";
      }
      this.commodityModificationStore = true;
      this.commodityModificationDis = false;
      this.showTabs = false;
    }
  },
  mounted() {
    this.brand(20, 1); //品牌的列表
    this.getClassType(); //商品分类列表
    this.findBrandList(); //单位的列表
    // this.goodDetail(); //商品详情
  },
  methods: {
    changeExpirationDate(val) {
      if (this.ruleForm.expirationDate != "") {
        if (
          this.ruleForm.expirationDate < 1 ||
          this.ruleForm.expirationDate > 3650
        ) {
          this.$message({
            type: "error",
            message: "保质期请输入1-3650的数字!"
          });
        }
      }
    },
    //配置权限
    setRole(key) {
      return util.selectTitle(this.power, key);
    },
    // 查看详情
    goodDetail() {
      let data = {
        id: util.getQuery("goosId")
      };
      getGoodsDetail(data).then(res => {
        this.ruleForm.name = res.data.name;
        this.ruleForm.brandName = res.data.brand;
        this.brandId = res.data.brandId;
        this.ruleForm.productCode = res.data.goodsCode;
        this.ruleForm.barCode = res.data.barCode;
        this.ruleForm.incomeTaxRates = res.data.incomeTaxRates;
        this.ruleForm.orgAllocated = res.data.orgAllocated;
        this.ruleForm.isAllot = res.data.isAllot;
        // this.ruleForm.isCommission = res.data.isCommission + ''
        this.ruleForm.commissionType = res.data.commissionWay + "";
        this.ruleForm.number = res.data.commissionValue;
        if (this.ruleForm.number == 0) {
          this.ruleForm.isCommission = "1";
        } else {
          this.ruleForm.isCommission = "0";
        }
        if (
          res.data.secendClassifyId == "" &&
          res.data.firstClassifyId == "" &&
          res.data.thirdClassifyId != ""
        ) {
          this.ruleForm.selectedOptions = [
            res.data.thirdClassifyId,
            res.data.secendClassifyId,
            res.data.firstClassifyId
          ];
        } else if (
          res.data.firstClassifyId == "" &&
          res.data.secendClassifyId != "" &&
          res.data.thirdClassifyId != ""
        ) {
          this.ruleForm.selectedOptions = [
            res.data.secendClassifyId,
            res.data.thirdClassifyId,
            res.data.firstClassifyId
          ];
        } else if (
          res.data.firstClassifyId != "" &&
          res.data.secendClassifyId != "" &&
          res.data.thirdClassifyId != ""
        ) {
          this.ruleForm.selectedOptions = [
            res.data.firstClassifyId,
            res.data.secendClassifyId,
            res.data.thirdClassifyId
          ];
        }

        this.status = res.data.status.toString();
        this.ruleForm.checked = this.status;
        if (this.ruleForm.checked == "1") {
          this.commodityModification = true;
          this.commodityModificationStore = false;
        }
        if (res.data.parameterLong != undefined) {
          this.specificationsList = res.data.parameterLong;
          let valueidde = [];
          for (var i = 0; i < res.data.parameter.length; i++) {
            valueidde.push(res.data.parameterLong[i].valueId);
          }
          this.detailvalueId = valueidde;
        }
        if (res.data.goodsPackParameter != undefined) {
          for (var i = 0; i < res.data.goodsPackParameter.length; i++) {
            res.data.goodsPackParameter[i].quantityBefor = "1";
            if (res.data.goodsPackParameter[i].isShow != "0") {
              this.isShow = i;
            }
          }
          this.tableDataUnitId = res.data.goodsPackParameter;
        }

        this.unitIdForm.unitId = res.data.goodsUnit;
        this.goodsUnitIdVals = res.data.goodsUnitId;
        this.unitIdData = res.data.goodsUnitId;
        if (res.data.expirationDate == undefined) {
          this.ruleForm.expirationDate = "";
        } else {
          this.ruleForm.expirationDate = res.data.expirationDate; //保质期
        }
        // this.ruleForm.retailState = res.data.retailState.toString();
        this.ruleForm.seasonalMarkingSwitch = res.data.isBatch.toString();
        if (this.ruleForm.seasonalMarkingSwitch == "1") {
          this.seasonalMarkingSwitchs = true;
        }
        this.ruleForm.whether = res.data.bulkBear.toString();
        if (res.data.isAllot == "1") {
          this.storeYin = false;
        }
        for (let i = this.ruleForm.selectedOptions.length; i > 0; i--) {
          if (this.ruleForm.selectedOptions[i] == undefined) {
            this.ruleForm.selectedOptions.splice(i, 1);
          }
        }
        if (this.setRole("商品知识")) {
          this.$refs.mychild.getDetail();
        }
      });
    },
    //标签页
    handleClick(tab, event) {
      // console.log(tab, event);
    },
    //单位请求数据
    findBrandList() {
      getGoodsUnitList().then(res => {
        this.options2 = res.data.list;
      });
    },
    //商品分类请求数据
    getClassType() {
      getGoodsClassifyTreeList({
        // shopId:this.merchantId
      }).then(res => {
        this.classType = res.data;
        this.goodDetail();
      });
    },
    // 品牌弹窗中的接口数据
    brand(pageSize, pageNum) {
      let data = {
        name: this.brandname,
        pageSize: pageSize,
        pageNo: pageNum,
        labelType: "0",
        shopId: this.merchantId
      };
      getGoodsLabelList(data).then(res => {
        this.total = res.data.total;
        this.tableData = res.data.list;
      });
    },
    // 品牌选择一条数据
    changeFun(val) {
      this.xzbrand = val;
    },
    //弹窗中选择品牌
    xzbrands() {
      if (this.xzbrand.name === undefined) {
        this.$message({
          type: "error",
          message: "请先选择品牌!"
        });
      } else {
        this.arr = this.xzbrand.id;
        this.arrname = this.xzbrand.name;
        this.dialogTableVisible = false;
        this.ruleForm.brandName = this.arrname.toString();
      }
    },
    // 品牌的搜索
    shopserch() {
      this.brandname = this.brandnames;
      this.brand(20, 1);
    },
    handleSizeChange(val) {
      this.pageSize = val;
      this.brand(val, this.currentPage);
    },
    handleCurrentChange(val) {
      this.currentPage = val;
      this.brand(this.pageSize, val);
    },
    //跳页
    toPage() {
      this.brand(this.pageSize, this.currentPage);
    },
    //保存所有数据接口
    save(formName) {
      if (
        this.ruleForm.isCommission == "0" &&
        (!this.ruleForm.number || this.ruleForm.number == 0)
      ) {
        this.$message.error("请输入提成值且大于0！");
        return;
      }
      if (this.ruleForm.orgAllocated !== '' || this.ruleForm.isAllot == '1') {
        if (this.setRole('商品知识')) {
          console.log('保存商品知识')
          this.$confirm('该商品已下发，基础信息、基础单位不能修改', '提示', {
            confirmButtonText: '保存商品知识',
            cancelButtonText: '取消'
          }).then(() => {
            let result = this.$refs.mychild.validKnoeledge()
            if (result != 'true') {
              this.$message.error(result)
              return
            }
            this.$nextTick(()=>{
              this.$refs.mychild.saveKnowledge (util.getQuery("goosId"))
            })
          }).catch(() => {});
          return;
        } else {

          this.$message.error('该商品已下发，基础信息、基础单位不能修改')
          return
        }
      }
      this.$refs[formName].validate(valid => {
        if (valid) {
          if (this.ruleForm.selectedOptions["1"] === undefined) {
            this.ruleForm.selectedOptions["1"] = "";
          }
          if (this.ruleForm.selectedOptions["2"] === undefined) {
            this.ruleForm.selectedOptions["2"] = "";
          }
          // if (this.indexI != "" || this.indexI == "0") {
          //   this.tableDataUnitId[this.indexI].isShow = "1";
          // }

          let selectedOptionsClass;
          if (
            this.ruleForm.selectedOptions[0] != "" &&
            this.ruleForm.selectedOptions[1] == "" &&
            this.ruleForm.selectedOptions[2] == ""
          ) {
            selectedOptionsClass = this.ruleForm.selectedOptions[0];
          } else if (
            this.ruleForm.selectedOptions[0] != "" &&
            this.ruleForm.selectedOptions[1] != "" &&
            this.ruleForm.selectedOptions[2] == ""
          ) {
            selectedOptionsClass = this.ruleForm.selectedOptions[1];
          } else if (
            this.ruleForm.selectedOptions[0] != "" &&
            this.ruleForm.selectedOptions[1] != "" &&
            this.ruleForm.selectedOptions[2] != ""
          ) {
            selectedOptionsClass = this.ruleForm.selectedOptions[2];
          }
          let valueId;
          if (this.specificationsValueArr.length > 0) {
            valueId = this.specificationsValueArr.toString();
          } else {
            valueId = this.detailvalueId.toString();
          }
          let arrBrandId;
          if (this.arr != "") {
            arrBrandId = this.arr;
          } else {
            arrBrandId = this.brandId;
          }
          let goodsunitIdval;
          if (this.unitIdval != "") {
            goodsunitIdval = this.unitIdval;
          } else {
            goodsunitIdval = this.goodsUnitIdVals;
          }
          if (this.tableDataUnitId.length > 0) {
            if (this.indexI != "" && this.indexI != "0") {
              if (this.tableDataUnitId[this.indexI] == undefined) {
                this.tableDataUnitId[0].isShow = "0";
              }
              if (this.tableDataUnitId[this.indexI] != undefined) {
                this.tableDataUnitId[this.indexI].isShow = "1";
                this.tableDataUnitId[0].isShow = "0";
              }
            } else if (this.indexI == "" || this.indexI == "0") {
              if (this.tableDataUnitId[0] != undefined) {
                this.tableDataUnitId[0].isShow = "1";
              }
            }
          }
          let data = {
            id: util.getQuery("goosId"),
            shopId: this.merchantId,
            status: this.ruleForm.checked,
            retailState: this.ruleForm.retailState,
            name: this.ruleForm.name,
            barCode: this.ruleForm.barCode,
            goodsCode: this.ruleForm.productCode,
            primaryClassifyId: selectedOptionsClass,
            goodsUnitId: goodsunitIdval,
            incomeTaxRates: this.ruleForm.incomeTaxRates,
            isBatch: this.ruleForm.seasonalMarkingSwitch,
            bulkBear: this.ruleForm.whether,
            goodsPackParameter: JSON.stringify(this.tableDataUnitId), //包装规格
            brandId: arrBrandId,
            orgAllocated: this.ruleForm.orgAllocated,
            valueId: valueId, //规格型号
            expirationDate: this.ruleForm.expirationDate, //保质期
            isCommission: this.ruleForm.isCommission, // 是否提成
            commissionWay: this.ruleForm.commissionType, // 提成方式
            commissionValue: this.ruleForm.number // 提成值
          };
          if (this.unitIdForm.unitId == "") {
            this.$message({
              type: "error",
              message: "请先选择单位!"
            });
          } else if (this.tableDataUnitId.length == "0") {
            this.$message({
              type: "error",
              message: "采供单位不能为空!"
            });
          } else if (this.tableDataUnitId.length > 0) {
            let a = true;
            let b = true;
            this.tableDataUnitId.forEach(item => {
              if (item.goodsUnitId == "") {
                a = false;
                return;
              }
              if (item.unitNum == "") {
                b = false;
                return;
              }
            });
            if (a == false) {
              this.$message({
                type: "error",
                message: "请先填写包装单位!"
              });
            } else if (b == false) {
              this.$message({
                type: "error",
                message: "请先填写换算后数量!"
              });
            } else {
              let value;
              let c = true;
              this.options2.forEach((item, i) => {
                this.tableDataUnitId.forEach(it => {
                  if (item.id == it.goodsUnitId) {
                    value = item.name;
                    if (value == it.baseUnitName && it.unitNum != 1) {
                      c = false;
                      return;
                    }
                  }
                });
              });
              if (c == false) {
                this.$message({
                  type: "error",
                  message: "换算单位相同,换算数量为1!"
                });
              } else if (this.ruleForm.expirationDate != "") {
                if (
                  this.ruleForm.expirationDate < 1 ||
                  this.ruleForm.expirationDate > 3650
                ) {
                  this.$message({
                    type: "error",
                    message: "保质期请输入1-3650的数字!"
                  });
                  return;
                }
                if (this.setRole("商品知识")) {
                  let result = this.$refs.mychild.validKnoeledge();
                  if (result != "true") {
                    this.$message.error(result);
                    return;
                  }
                }
                  updateGoods(data).then(res => {
                    if (res.code == 200) {
                      if (this.setRole('商品知识')) {
                        this.$refs.mychild.saveKnowledge (util.getQuery("goosId"))
                      } else {
                      util.routerTo(
                        "/operate-management/goods-management/goods-goodslist"
                      );
                    }
                  }
                });
              } else {
                if (this.setRole("商品知识")) {
                  let result = this.$refs.mychild.validKnoeledge();
                  if (result != "true") {
                    this.$message.error(result);
                    return;
                  }
                }
                updateGoods(data).then(res => {
                  if (res.code == 200) {
                    if (this.setRole("商品知识")) {
                      this.$refs.mychild.saveKnowledge(util.getQuery("goosId"));
                    } else {
                      util.routerTo(
                        "/operate-management/goods-management/goods-goodslist"
                      );
                    }
                  }
                });
              }
            }
          }
        } else {
          this.$message.error("有信息未填写");
          return false;
        }
      });
    },
    // 返回按钮
    goBack() {
      this.$confirm('您确认要离开该页面吗，您输入的数据可能不会被保存？', '确认关闭', {
        confirmButtonText: '确定',
        cancelButtonText: '取消'
      }).then(() => {
         util.routerTo(
                        "/operate-management/goods-management/goods-goodslist"
                      );
      }).catch(() => {
      })
    },
    // 添加规格型号
    addsize() {
      this.dialogTableVisible1 = true;
      this.SpecificationsLists(this.pageSizeSpe, this.currentPageSpe);
    },
    // 规格型号的显示数组
    SpecificationsLists(pageSize, pageNum) {
      let data = {};
      if (this.soUrce == "5") {
        data = {
          pageSize: pageSize,
          pageNo: pageNum,
          shopId: this.merchantId,
          paramName: this.specifications
        };
      } else {
        data = {
          pageSize: pageSize,
          pageNo: pageNum,
          paramName: this.specifications
        };
      }
      getGoodsParameterListByPage(data).then(res => {
        this.tableDataSpecifications = res.data.list;
        this.totalSpe = res.data.total;
      });
    },
    specificationsSerch() {
      this.SpecificationsLists(this.pageSizeSpe, 1);
    },
    // 规格型号选择的数组
    changeFunSpecifications(val) {
      this.specificationsValue = val;
      // console.log(this.specificationsValue)
      // tableDataSpecifications
    },
    // 规格型号确定
    toPageSpecifications() {
      this.SpecificationsLists(this.pageSizeSpe, this.currentPageSpe);
    },
    handleSizeChangeSpecifications(val) {
      this.pageSizeSpe = val;
      this.SpecificationsLists(val, this.currentPageSpe);
    },
    handleCurrentChangeSpecifications(val) {
      this.currentPageSpe = val;
      this.SpecificationsLists(this.pageSizeSpe, val);
    },
    // 取消
    cancelSpe() {
      this.dialogTableVisible1 = false;
    },
    // 规格型号确定选择的数据
    submitFormSpe() {
      // this.dialogTableVisible1 = false;
      for (var i = 0; i < this.specificationsValue.length; i++) {
        this.specificationsValue[i].nameId = this.specificationsValue[i].id;
        for (var j = 0; j < this.specificationsValue[i].value.length; j++) {
          if (
            this.specificationsValue[i].radiospe ==
            this.specificationsValue[i].value[j].id
          ) {
            this.$set(
              this.specificationsValue[i],
              "paramValue",
              this.specificationsValue[i].value[j].paramValue
            );
          }
        }
      }
      let specificationsValues = this.specificationsValue;
      let arr = [];
      for (var i = 0; i < this.specificationsValue.length; i++) {
        arr.push(this.specificationsValue[i].radiospe);
      }
      this.specificationsValueArr = arr;
      let a = true;
      this.specificationsValueArr.forEach(item => {
        if (item == undefined) {
          a = false;
          return;
        }
      });
      if (a == false) {
        this.$message({
          type: "error",
          message: "请先选择规格型号值!"
        });
      } else {
        this.dialogTableVisible1 = false;
        this.specificationsList = specificationsValues.concat(
          this.specificationsList
        );
        this.specificationsList = this.unique(this.specificationsList);
      }
    },

    unique(arr) {
      const res = new Map();
      return arr.filter(arr => !res.has(arr.nameId) && res.set(arr.nameId, 1));
    },
    // 包装规格添加
    addUnitId() {
      for (var i = 0; i < this.options2.length; i++) {
        if (this.unitIdval == "") {
          this.unitIdName = this.unitIdForm.unitId;
        } else if (this.options2[i].id == this.unitIdval) {
          this.unitIdName = this.options2[i].name;
        }
      }

      if (this.unitIdForm.unitId != "") {
        let newele = {
          quantityBefor: "1",
          goodsUnitId: "",
          unitNum: "",
          baseUnitName: this.unitIdName,
          isShow: "0"
        };
        // this.tableDataUnitId.unshift(newele);
        this.tableDataUnitId.push(newele);
      } else {
        this.$message({
          type: "error",
          message: "请先选择基本单位!"
        });
      }
    },
    changeCheckbox(index, row) {
      this.indexI = index;
    },
    // 修改
    handleEditUnitId() {
      this.tableData[i].show = true;
    },
    // 删除
    cancelUnitId(index, rows) {
      rows.splice(index, 1);
      if (this.isShow[index] != undefined) {
        this.isShow[index] = "0";
      }
    },
    // 选择的单位
    changeUnitId(val) {
      this.unitIdval = val;
      if (this.unitIdData != val) {
        this.tableDataUnitId = [];
        this.indexI = "";
      }
      //  else if (this.unitIdData == val) {
      //   this.tableDataUnitId = this.adds;
      // }
      // if(val){
      //   this.tableDataUnitId = [];
      //   this.indexI=""
      // }
      for (var i = 0; i < this.options2.length; i++) {
        if (this.options2[i].id == val) {
          this.unitIdName = this.options2[i].name;
        }
      }
      for (var i = 0; i < this.tableDataUnitId.length; i++) {
        this.tableDataUnitId[i].baseUnitName = this.unitIdName;
      }
      if (this.unitIdData != val) {
        let newele = {
          quantityBefor: "1",
          goodsUnitId: val,
          unitNum: "1",
          baseUnitName: this.unitIdName,
          isShow: "0",
          show: true
        };
        this.tableDataUnitId.push(newele);
        this.tableDataUnitId.forEach((item, i) => {
          if (this.indexI == "") {
            this.isShow = i;
          }
        });
      }
    },
    // 修改
    goodEdit() {
      if (this.setRole("商品知识")) {
        this.$refs.mychild.setShowTab("3");
      }
      if (this.ruleForm.checked == "0") {
        this.$set(this, "showTab", "3");
        this.showTabs = true;
        this.commodityModificationDis = false;
        this.commodityModification = false;
        this.commodityModificationStore = false;
      } else if (this.ruleForm.checked == "1") {
        this.$set(this, "showTab", "3");
        this.showTabs = true;
        this.commodityModificationStore = false;
      }
      this.$router.push({
        query: merge(this.$route.query, { showTab: "3" })
      });
    }
  }
};
</script>
<style scoped>
.span {
  font-size: 13px;
  color: #333;
}
.infon_text {
  padding: 10px;
}
.serch {
  margin-top: 0;
}
.goodsFooter {
  margin: 0 auto;
  text-align: center;
}
.goodsgoodEditnew .from_main .el-input {
  width: 220px;
}
</style>
<style>
.addshopname .paramInput .el-input {
  width: 130px;
}
.goodsbatchs .el-input-group--prepend .el-input__inner,
.el-input-group__append {
  border: solid 1px #579ff8;
  background-color: #579ff8;
  color: #ffffff;
}
.addshopname .pageinput .el-input {
  width: 85px;
}
.addshopname .pageinput .el-pagination__editor.el-input .el-input__inner {
  height: 28px;
  width: 57px;
}

.from_main .rowsecond .el-input {
  width: 220px;
}
.from_main .rowsecondSpan .el-input {
  width: 90px;
}
.from_main .rowsecondSpan span {
  margin-left: -15px;
}
.cascaderClass .el-input.is-disabled .el-input__inner {
  background-color: #f8f8f8 !important;
  border-color: #f8f8f8 !important;
}
.cascaderClass .el-input__suffix {
  display: none !important;
}
.cascaderClass .el-cascader__label {
  color: #666 !important;
}
</style>




